﻿using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using InspectionApi.Enum;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using netCoreStudy.Dto;
using netCoreStudy.Entities;
using netCoreStudy.Entities.Base;
using netCoreStudy.IService;

namespace netCoreStudy.Controllers
{
	/// <summary>
	/// 文件
	/// </summary>
	[ApiController]
	[Route("api/material")]
	public class MaterialController : ControllerBase
	{
		private readonly ILogger<MaterialController> _logger;
		private readonly IMapper _mapper;
		private readonly IMaterialService _materialService;

		public MaterialController(ILogger<MaterialController> logger,
			IMapper mapper,
			IMaterialService materialService)
		{
			_logger = logger;
			_mapper = mapper;
			_materialService = materialService;
		}


		/// <summary>
		/// 文件上传 
		/// </summary>
		/// <param name="addMaterialDto"></param>
		/// <returns></returns>
		[HttpPost]
		public async Task<IActionResult> AddOne([FromForm] AddMaterialDto addMaterialDto)
		{
			string fileName = addMaterialDto.File.FileName;
			string prefix = fileName.Split('.')[0];
			string suffix = fileName.Split('.')[1];
			string[] imgSuffixs = {"jpeg", "jpg", "png"};
			string realName =
				$"{prefix}-{(long) DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalMilliseconds}";
			string fileRootPath = Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot", "file");
			//不存在文件目录先创建 
			if (!Directory.Exists(fileRootPath))
			{
				Directory.CreateDirectory(fileRootPath);
			}

			string path = Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot","file",
				$"{realName}.{suffix}");
			Console.WriteLine(path);
			await using (Stream stream = new FileStream(path, FileMode.Create))
			{
				await addMaterialDto.File.CopyToAsync(stream);
			}

			//
			Material material = _mapper.Map<Material>(addMaterialDto);
			material.RealName = realName;
			material.Suffix = suffix;
			material.Path = path;
			material.Type = imgSuffixs.Contains(suffix.ToLower()) ? FileType.图片 : FileType.其他;
			material.Size = addMaterialDto.File.Length;
			_materialService.Add(material);
			await _materialService.SaveAsync();
			MaterialDto materialDto = _mapper.Map<MaterialDto>(material);
			return this.SuccessMsg("添加成功!", materialDto);
		}
	}
}